package com.kbbywyclient.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.data.entity.AccountInfo;
import com.kbbywyclient.data.entity.MinePromotion;
import com.kbbywyclient.data.entity.User;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.MinePromotionModule;
import com.kbbywyclient.presenter.MinePromotionPresenter;
import com.kbbywyclient.service.ApiServiceHelper;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.MinePromotionContract;
import com.kbbywyclient.ui.helper.ShareHelper;
import com.kbbywyclient.ui.pop.SharePopWin;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.FileUtils;
import com.kbbywyclient.util.QrCodeUtils;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomDialog;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by Jiangzx on 2017/9/6 14:30.
 */

public class MinePromotionActivity extends BaseActivity implements MinePromotionContract.View {
    private static final int COLOR_LEVEL_DISTRIBUTOR=0XFFFFF000;
    private static final int COLOR_LEVEL_FIRST=0XFF00FF6C;
    private static final int COLOR_LEVEL_SECOND=0XFF019EDF;
    private static final int COLOR_LEVEL_NORMAL=0XFF009E96;

    @BindView(R.id.iv_level)
    ImageView ivLevel;
    @BindView(R.id.tv_level)
    TextView tvLevel;

    @BindView(R.id.tv_total_balance)
    TextView tvTotalBalance;

    @BindView(R.id.tv_month_income)
    TextView tvMonthIncome;
    @BindView(R.id.tv_total_income)
    TextView tvTotalIncome;
    @BindView(R.id.tv_month_partner)
    TextView tvMonthPartner;
    @BindView(R.id.tv_total_partner)
    TextView tvTotalPartner;
    @BindView(R.id.iv_share_qr_code)
    ImageView ivShareQrCode;
    @BindView(R.id.tv_invite_code)
    TextView tvInviteCode;
    @BindView(R.id.tv_share_des)
    TextView tvShareDes;
    @Inject
    MinePromotionPresenter presenter;

    private ShareHelper shareHelper;
    private String shareUrl;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_mine_promotion;
    }

    @Override
    protected void initView() {
        int role=getUser().getRole();
        if(role==Constants.LEVEL_FIRST||role==Constants.LEVEL_SECOND){
            //二维码
            String click="设置与合伙人奖金分成";
            //分享描述
            String shareDes="多分享多收益，邀请您的好友注册卡贝贝，打造自己的创业团队！" +click+
                    "\n\n" +
                    "方式一：识别二维码一起玩：长按保存专属二维码分享给好友，或让好友直接扫码，打开注册页面即可识别由您推荐；\n"+
                    "方式二：手机号码邀请：好友下载卡贝贝注册时填上您的邀请码，即可识别；\n"+
                    "方式三：H5营销分享页：分享专属注册页面给朋友即可识别；";
            int start=shareDes.indexOf("设置与合伙人奖金分成");
            int end=start+click.length();
            SpannableStringBuilder sb=new SpannableStringBuilder(shareDes);
            sb.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(0XFF00C8E0);
                    ds.setUnderlineText(false);
                }

                @Override
                public void onClick(View widget) {
                    presenter.getSepPercent(getUser().getSalesID(),
                            MinePromotionContract.Presenter.ACTION_SET_REWARD_CLICK);
                }
            },start,end,Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            sb.setSpan(new ForegroundColorSpan(0XFF00C8E0),start,end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            tvShareDes.setHighlightColor(0X00000000);
            tvShareDes.setMovementMethod(LinkMovementMethod.getInstance());
            tvShareDes.setText(sb);
        }else{
            //分享描述
            String shareDes="多分享多收益，邀请您的好友注册卡贝贝，打造自己的创业团队！" +
                    "\n\n" +
                    "方式一：识别二维码一起玩：长按保存专属二维码分享给好友，或让好友直接扫码，打开注册页面即可识别由您推荐；\n"+
                    "方式二：手机号码邀请：好友下载卡贝贝注册时填上您的邀请码，即可识别；\n"+
                    "方式三：H5营销分享页：分享专属注册页面给朋友即可识别；";
            tvShareDes.setText(shareDes);
        }


        tvTotalBalance.setText(R.string.text_default_txt_value);
        tvMonthIncome.setText(R.string.text_default_txt_value);
        tvTotalIncome.setText(R.string.text_default_txt_value);
        tvMonthPartner.setText(R.string.text_default_txt_value);
        tvTotalPartner.setText(R.string.text_default_txt_value);
        tvInviteCode.setText(R.string.text_default_txt_value);

    }

    @Override
    public void initData() {
        User user=getUser();
        int role=user.getRole();
        int salesId=user.getSalesID();
        if((role==Constants.LEVEL_FIRST||role==Constants.LEVEL_SECOND)&&
                PreUtils.isFirstToPromotion(MinePromotionActivity.this)) {
            PreUtils.setFirstToPromotion(MinePromotionActivity.this);
            presenter.getSepPercent(salesId, MinePromotionContract.Presenter.ACTION_FIRST_ENTER);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("我的推广");
        presenter.getPromotionData(PreUtils.getUser(MinePromotionActivity.this).getSalesID());
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getMinePromotionComponent(new MinePromotionModule(this)).inject(this);
    }

    @OnClick({R.id.iv_back,R.id.tv_withdraw_detail,
            R.id.bt_withdraw,R.id.ll_mine_client,R.id.ll_partner})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_withdraw_detail:
                ActivitySkipUtil.skipAnotherActivity(MinePromotionActivity.this,
                        WithdrawMoneyRecordActivity.class);
                break;
            case R.id.bt_withdraw:
                //提现
                presenter.getWithdrawRule();
                break;
            case R.id.ll_mine_client:
                //我的客户
                ActivitySkipUtil.skipAnotherActivity(MinePromotionActivity.this,
                        MineClientActivity.class);
                break;
            case R.id.ll_partner:
                //合伙人
                ActivitySkipUtil.skipAnotherActivity(MinePromotionActivity.this,
                        MinePartnerActivity.class);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(shareHelper!=null){
            shareHelper.onActivityResult(requestCode,resultCode,data);
        }
    }

    private void share(int action){
            shareHelper =
                    new ShareHelper(MinePromotionActivity.this, "我的推广");
            ShareHelper.ShareBody shareBody = new ShareHelper.ShareBody();
            shareBody.title = "我正在分享办卡赚钱，一起成为合伙人，把人脉变钱啦！";
            shareBody.url = shareUrl;
            switch (action) {
                case MinePromotionContract.Presenter.ACTION_SHARE_WX:
                    //微信
                    shareBody.platForm = SharePopWin.PLATFORM_WX;
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_WX_CIRCLE:
                    //微信朋友圈
                    shareBody.platForm = SharePopWin.PLATFORM_WX_CIRCLE;
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_QQ:
                    //QQ
                    shareBody.platForm = SharePopWin.PLATFORM_QQ;
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_SINA:
                default:
                    //新浪微博
                    shareBody.platForm = SharePopWin.PLATFORM_SINA;
                    break;
            }
            shareHelper.share(shareBody);
    }

    @OnClick({R.id.tv_share_wx,R.id.tv_share_wx_circle,R.id.tv_share_qq,R.id.tv_share_sina})
    public void onShareClick(View view){
        if(!TextUtils.isEmpty(shareUrl)) {
            User user=getUser();
            int userId=user.getSalesID();
            int role=user.getRole();
            if(role==Constants.LEVEL_FIRST||role==Constants.LEVEL_SECOND){
                //一级、二级合伙人
                switch (view.getId()) {
                    case R.id.tv_share_wx:
                        //微信
                        presenter.getSepPercent(userId,MinePromotionContract.Presenter.ACTION_SHARE_WX);
                        break;
                    case R.id.tv_share_wx_circle:
                        //微信朋友圈
                        presenter.getSepPercent(userId,MinePromotionContract.Presenter.ACTION_SHARE_WX_CIRCLE);
                        break;
                    case R.id.tv_share_qq:
                        //QQ
                        presenter.getSepPercent(userId,MinePromotionContract.Presenter.ACTION_SHARE_QQ);
                        break;
                    case R.id.tv_share_sina:
                        //新浪微博
                        presenter.getSepPercent(userId,MinePromotionContract.Presenter.ACTION_SHARE_SINA);
                        break;
                }
            }else{
                switch (view.getId()) {
                    case R.id.tv_share_wx:
                        //微信
                        share(MinePromotionContract.Presenter.ACTION_SHARE_WX);
                        break;
                    case R.id.tv_share_wx_circle:
                        //微信朋友圈
                        share(MinePromotionContract.Presenter.ACTION_SHARE_WX_CIRCLE);
                        break;
                    case R.id.tv_share_qq:
                        //QQ
                        share(MinePromotionContract.Presenter.ACTION_SHARE_QQ);
                        break;
                    case R.id.tv_share_sina:
                        //新浪微博
                        share(MinePromotionContract.Presenter.ACTION_SHARE_SINA);
                        break;
                }
            }
        }
    }

    private CustomDialog saveQrCodeDialog;
    @OnLongClick(R.id.iv_share_qr_code)
    public boolean onLongClick(View view){
        if(!TextUtils.isEmpty(shareUrl)){
            final Context context=MinePromotionActivity.this;
            saveQrCodeDialog=new CustomDialog(context,
                    R.style.Customdialog,
                    "卡贝贝提示",
                    "保存二维码到手机", new CustomDialog.ButtonListener() {
                @Override
                public void left() {
                    saveQrCodeDialog.dismiss();
                }

                @Override
                public void right() {
                    saveQrCodeDialog.dismiss();
                    showLoadingDialog(getString(R.string.text_wait_a_moment));
                    //保存二维码
                    final int qrCodeSize = StringUtil.dip2px(300);
                    ApiServiceHelper.
                            appointThreadNormal(
                                    Observable.from(new String[]{shareUrl}).
                                            map(new Func1<String, Bitmap>() {
                                                @Override
                                                public Bitmap call(String s) {
                                                    Bitmap bitmap=QrCodeUtils.generateQrCode(s,qrCodeSize,qrCodeSize);
                                                    if(bitmap!=null){
                                                        BufferedOutputStream bos=null;
                                                        try{
                                                            File dir=new File(FileUtils.imagePath);
                                                            if(!dir.exists()){
                                                                dir.mkdirs();
                                                            }
                                                            File file=new File(dir,"distribution_invite_qr_code.jpg");
                                                            if(!file.exists()){
                                                                file.delete();
                                                            }
                                                            bos=new BufferedOutputStream(new FileOutputStream(file));
                                                            bitmap.compress(Bitmap.CompressFormat.JPEG,
                                                                    100,bos);
                                                            //保存成功后，发送广播到相册
                                                            MediaScannerConnection.scanFile(
                                                                    MinePromotionActivity.this,
                                                                    new String[]{file.getAbsolutePath()},
                                                                    new String[]{"image/jpeg"},
                                                                    null);
                                                        }catch (Exception e){
                                                            return null;
                                                        }finally {
                                                            if(bos!=null){
                                                                try {
                                                                    bos.close();
                                                                } catch (IOException e) {
                                                                    e.printStackTrace();
                                                                }
                                                            }
                                                        }
                                                    }
                                                    return bitmap;
                                                }
                                            })).
                            subscribe(new Subscriber<Bitmap>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {
                                    //保存失败
                                    closeLoadingDialog();
                                }

                                @Override
                                public void onNext(Bitmap bitmap) {
                                    closeLoadingDialog();
                                    //保存成功
                                    if(bitmap==null){
                                        ToastUtil.showShort("保存二维码失败");
                                    }else{
                                        ToastUtil.showShort("保存成功");
                                    }
                                }
                            });
                }
            },"取消","确定");
            if(!saveQrCodeDialog.isShowing()){
                saveQrCodeDialog.show();
            }
        }
        return true;
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    CustomDialog notBindCardDialog;
    @Override
    public void showNotBindCardDialog() {
        if(notBindCardDialog==null){
            notBindCardDialog=new CustomDialog(this,
                    R.style.Customdialog,
                    "卡贝贝提示",
                    "你尚未绑定银行卡，请先绑卡", new CustomDialog.ButtonListener() {
                @Override
                public void left() {
                    notBindCardDialog.dismiss();
                }

                @Override
                public void right() {
                    notBindCardDialog.dismiss();
                    toBindCardActivity();
                }
            },"取消","确定");
        }
        if(!notBindCardDialog.isShowing()){
            notBindCardDialog.show();
        }
    }

    @Override
    public void setPromotionData(MinePromotion promotion) {
        int role = promotion.getRole();
        Context context = MinePromotionActivity.this;
        User user = PreUtils.getUser(context);
        user.setRole(role);
        PreUtils.saveUser(context, user);
        switch (role) {
            case Constants.LEVEL_DISTRIBUTOR:
                //总代理
                ivLevel.setImageResource(R.mipmap.icon_level_1);
                tvLevel.setText("总代理");
                tvLevel.setTextColor(COLOR_LEVEL_DISTRIBUTOR);
                break;
            case Constants.LEVEL_FIRST:
                //一级合伙人
                ivLevel.setImageResource(R.mipmap.icon_level_2);
                tvLevel.setText("一级合伙人");
                tvLevel.setTextColor(COLOR_LEVEL_FIRST);
                break;
            case Constants.LEVEL_SECOND:
                //二级合伙人
                ivLevel.setImageResource(R.mipmap.icon_level_3);
                tvLevel.setText("二级合伙人");
                tvLevel.setTextColor(COLOR_LEVEL_SECOND);
                break;
            case Constants.LEVEL_NORMAL:
                //普通合伙人
                ivLevel.setImageResource(R.mipmap.icon_level_4);
                tvLevel.setText("普通合伙人");
                tvLevel.setTextColor(COLOR_LEVEL_NORMAL);
                break;
        }
        //保留两位小数
        tvTotalBalance.setText(String.format(Locale.CHINESE,
                Constants.AMOUNT_FORMAT,
                promotion.getBalance()));

        tvMonthIncome.setText("本月收入：" + promotion.getP1_mouth());
        tvTotalIncome.setText("总收入：" + promotion.getP1_total());
        if (role == Constants.LEVEL_DISTRIBUTOR || role == Constants.LEVEL_NORMAL) {
            tvMonthPartner.setText("本月结算客户：" + promotion.getP2_mouth());
            tvTotalPartner.setText("总结算客户：" + promotion.getP2_total());
        } else {
            tvMonthPartner.setText("我的本月奖金：" + promotion.getP2_mouth());
            tvTotalPartner.setText("总奖金：" + promotion.getP2_total());
        }

        final int qrCodeSize = StringUtil.dip2px(115);
        shareUrl = API.WEB_ADDRESS + promotion.getShareURL();
        //生成二维码
        ApiServiceHelper.
                appointThreadNormal(
                        Observable.from(new String[]{shareUrl}).
                                map(s -> QrCodeUtils.generateQrCode(s, qrCodeSize, qrCodeSize))
                ).
                subscribe(new Subscriber<Bitmap>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtil.showShort("生成二维码失败");
                    }

                    @Override
                    public void onNext(Bitmap bitmap) {
                        ivShareQrCode.setImageBitmap(bitmap);
                    }
                });

        tvInviteCode.setText("专属邀请码：" + promotion.getInviteCode());

    }

    @Override
    public void toBindCardActivity() {
        ActivitySkipUtil.skipAnotherActivity(MinePromotionActivity.this,
                CardHolderInfoActivity.class);
    }

    @Override
    public void toWithdrawActivity(AccountInfo accountInfo, double miniAmount, double maxAmount) {
        HashMap<String,Object> params=new HashMap<>();
        try{
            params.put(CommissionWithdrawActivity.BALANCE_D,Double.parseDouble(accountInfo.getBalance()));
        }catch (Exception e){
            e.printStackTrace();
        }
        params.put(CommissionWithdrawActivity.RULE_MINI_D,miniAmount);
        params.put(CommissionWithdrawActivity.RULE_MAX_D,maxAmount);
        AccountInfo.BankCardInfo cardInfo=accountInfo.getBankcardInfo();
        params.put(CommissionWithdrawActivity.BANK_NAME_S,cardInfo.getBank_name());
        params.put(CommissionWithdrawActivity.CARD_LOGO_S,cardInfo.getBank_logo());
        params.put(CommissionWithdrawActivity.CARD_NUMBER_S,cardInfo.getAlipay_account());
        params.put(CommissionWithdrawActivity.CARD_TYPE_I,cardInfo.getCard_type());
        ActivitySkipUtil.skipAnotherActivity(MinePromotionActivity.this,
                CommissionWithdrawActivity.class,params);
    }

    @Override
    public void onSepPercentSuccess(String percent,int action) {
        if(TextUtils.isEmpty(percent)){
            //未设置合伙人奖金分成
            switch (action){
                case MinePromotionContract.Presenter.ACTION_FIRST_ENTER:
                    //第一次进入“我的推广”
                    showSetRewardDialog(action);
                    break;
                case MinePromotionContract.Presenter.ACTION_SET_REWARD_CLICK:
                    //设置合伙人奖金分成
                    toSetRewardPercent(percent);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_WX:
                    //分享给微信好友
                    showSetRewardDialog(action);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_WX_CIRCLE:
                    //分享到微信朋友圈
                    showSetRewardDialog(action);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_QQ:
                    //分享到QQ
                    showSetRewardDialog(action);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_SINA:
                    //分享到新浪微博
                    showSetRewardDialog(action);
                    break;
            }
        }else{
            //已设置合伙人奖金分成
            switch (action){
                case MinePromotionContract.Presenter.ACTION_FIRST_ENTER:
                    //第一次进入“我的推广”
                    //无需处理
                    break;
                case MinePromotionContract.Presenter.ACTION_SET_REWARD_CLICK:
                    //设置合伙人奖金分成
                    toSetRewardPercent(percent);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_WX:
                    //分享给微信好友
                    share(action);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_WX_CIRCLE:
                    //分享到微信朋友圈
                    share(action);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_QQ:
                    //分享到QQ
                    share(action);
                    break;
                case MinePromotionContract.Presenter.ACTION_SHARE_SINA:
                    //分享到新浪微博
                    share(action);
                    break;
            }
        }
    }


    //去设置合伙人奖金分成
    private void toSetRewardPercent(String percent){
        HashMap<String, Object> params = new HashMap<>();
        if(percent!=null){
            params.put(SetRewardActivity.SEP_PERCENT_S, percent);
        }
        ActivitySkipUtil.skipAnotherActivity(MinePromotionActivity.this,
                SetRewardActivity.class, params);
    }

    private CustomDialog setRewardDialog;
    @Override
    public void showSetRewardDialog(final int action) {
        Context context = MinePromotionActivity.this;
        setRewardDialog = new CustomDialog(context,
                R.style.Customdialog,
                "卡贝贝提示",
                "邀请您的好友注册卡贝贝、邀请好友办卡，您可获取奖金！现在去设置合伙人奖金分成？",
                new CustomDialog.ButtonListener() {
                    @Override
                    public void left() {
                        setRewardDialog.dismiss();
                        if(action!=MinePromotionContract.Presenter.ACTION_FIRST_ENTER){
                            share(action);
                        }
                    }

                    @Override
                    public void right() {
                        setRewardDialog.dismiss();
                        toSetRewardPercent(null);
                    }
                }, "下次再设", "去设置");

        if (!isFinishing() && !setRewardDialog.isShowing()) {
            setRewardDialog.show();
        }
    }
}
